import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import './storeDetail.css';
import { Star, AddComment, Business, ArrowBack } from '@material-ui/icons';
import { 
  Pagination, 
  TextField, 
  Button, 
  Card, 
  CardContent, 
  Typography,
  IconButton
} from '@mui/material';

// 导入完整的商家数据
const mockStores = [
  {
    id: 1,
    name: "The Coffee House",
    image: "https://images.unsplash.com/photo-1445116572660-236099ec97a0",
    location: "123 Main Street",
    rating: 4.7,
    comments: 12,
    businessHours: "9:00 AM - 10:00 PM",
    type: "cafe"
  },
  {
    id: 2,
    name: "Urban Bistro",
    image: "https://images.unsplash.com/photo-1470337458703-46ad1756a187",
    location: "456 Park Avenue",
    rating: 4.7,
    comments: 15,
    businessHours: "11:00 AM - 11:00 PM",
    type: "restaurant"
  },
  {
    id: 3,
    name: "The Social Club",
    image: "https://images.unsplash.com/photo-1514933651103-005eec06c04b",
    location: "789 Broadway",
    rating: 4.8,
    comments: 28,
    businessHours: "5:00 PM - 2:00 AM",
    type: "bar"
  },
  {
    id: 4,
    name: "Sunset Lounge",
    image: "https://images.unsplash.com/photo-1566737236500-c8ac43014a67",
    location: "321 Ocean Drive",
    rating: 4.6,
    comments: 22,
    businessHours: "4:00 PM - 12:00 AM",
    type: "club"
  },
  {
    id: 5,
    name: "City Pub",
    image: "https://images.unsplash.com/photo-1572116469696-31de0f17cc34",
    location: "567 Downtown Street",
    rating: 4.5,
    comments: 18,
    businessHours: "12:00 PM - 2:00 AM",
    type: "bar"
  },
  {
    id: 6,
    name: "Art Gallery Cafe",
    image: "https://images.unsplash.com/photo-1501339847302-ac426a4a7cbb",
    location: "890 Culture Avenue",
    rating: 4.9,
    comments: 32,
    businessHours: "10:00 AM - 8:00 PM",
    type: "cafe"
  },
  {
    id: 7,
    name: "Jazz & Wine",
    image: "https://images.unsplash.com/photo-1514933651103-005eec06c04b",
    location: "432 Music Lane",
    rating: 4.8,
    comments: 25,
    businessHours: "6:00 PM - 1:00 AM",
    type: "bar"
  },
  {
    id: 8,
    name: "Garden Terrace",
    image: "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4",
    location: "765 Green Street",
    rating: 4.6,
    comments: 20,
    businessHours: "11:00 AM - 10:00 PM",
    type: "restaurant"
  },
  {
    id: 9,
    name: "Moonlight Club",
    image: "https://images.unsplash.com/photo-1578736641330-3155e606cd40",
    location: "123 Night Avenue",
    rating: 4.7,
    comments: 30,
    businessHours: "9:00 PM - 4:00 AM",
    type: "club"
  },
  {
    id: 10,
    name: "Bistro Italiano",
    image: "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4",
    location: "789 Italian Street",
    rating: 4.8,
    comments: 45,
    businessHours: "11:00 AM - 11:00 PM",
    type: "restaurant"
  },
  {
    id: 11,
    name: "Zen Tea House",
    image: "https://images.unsplash.com/photo-1445116572660-236099ec97a0",
    location: "456 Peace Road",
    rating: 4.9,
    comments: 38,
    businessHours: "8:00 AM - 8:00 PM",
    type: "cafe"
  },
  {
    id: 12,
    name: "The Vintage Bar",
    image: "https://images.unsplash.com/photo-1572116469696-31de0f17cc34",
    location: "321 Classic Street",
    rating: 4.6,
    comments: 28,
    businessHours: "4:00 PM - 2:00 AM",
    type: "bar"
  }
];

export default function StoreDetail() {
  const { storeId } = useParams();
  const navigate = useNavigate();
  const [page, setPage] = useState(1);
  const [storeDetail, setStoreDetail] = useState(null);
  const [newReview, setNewReview] = useState({
    rating: 5,
    content: ''
  });
  const reviewsPerPage = 10;

  useEffect(() => {
    console.log('Current storeId:', storeId); // 调试日志
    const store = mockStores.find(store => store.id === parseInt(storeId));
    console.log('Found store:', store); // 调试日志
    
    if (store) {
      setStoreDetail({
        ...store,
        reviews: Array(50).fill(null).map((_, index) => ({
          id: index + 1,
          user: `User${index + 1}`,
          date: "2024/03/20",
          rating: (4 + Math.random()).toFixed(1),
          content: [
            "Great atmosphere and excellent service! The staff is very friendly and professional.",
            "Amazing place! The ambiance is perfect and the quality is outstanding.",
            "One of my favorite places in the city. Highly recommended!",
            "Regular customer here. Never disappointed with their service.",
            "Wonderful experience every time I visit. Keep up the good work!"
          ][index % 5]
        }))
      });
    }
  }, [storeId]);

  const handleBack = () => {
    navigate('/');
  };

  const handlePageChange = (event, value) => {
    setPage(value);
    document.querySelector('.reviewSection').scrollIntoView({ behavior: 'smooth' });
  };

  const handleReviewSubmit = (e) => {
    e.preventDefault();
    console.log('Submit review:', newReview);
    setNewReview({ rating: 5, content: '' });
  };

  const currentReviews = storeDetail?.reviews?.slice(
    (page - 1) * reviewsPerPage,
    page * reviewsPerPage
  ) || [];

  const renderStars = (rating) => {
    return [...Array(5)].map((_, index) => (
      <Star 
        key={index} 
        className={index < Math.floor(rating) ? "star-filled" : "star-empty"} 
        onClick={() => setNewReview({...newReview, rating: index + 1})}
        style={{ cursor: 'pointer' }}
      />
    ));
  };

  if (!storeDetail) {
    return (
      <div className="storeDetail">
        <div className="loadingContainer">
          <IconButton onClick={handleBack} className="backButton">
            <ArrowBack />
          </IconButton>
          <Typography variant="h6">Loading store details...</Typography>
        </div>
      </div>
    );
  }

  return (
    <div className="storeDetail">
      <IconButton 
        onClick={handleBack}
        className="backButton"
        sx={{ position: 'absolute', top: 20, left: 20, backgroundColor: 'rgba(255, 255, 255, 0.8)' }}
      >
        <ArrowBack />
      </IconButton>

      <div className="storeImageBanner">
        <img src={storeDetail.image} alt={storeDetail.name} />
      </div>
      
      <div className="storeContent">
        <div className="storeHeader">
          <h1>{storeDetail.name}</h1>
          <div className="storeRating">
            {renderStars(storeDetail.rating)}
            <span className="ratingNumber">{storeDetail.rating}</span>
          </div>
        </div>

        <div className="storeInfo">
          <div className="infoItem">
            <label>Business Hours:</label>
            <span>{storeDetail.businessHours}</span>
          </div>
          <div className="infoItem">
            <label>Address:</label>
            <span>{storeDetail.location}</span>
          </div>
          <div className="infoItem">
            <label>Type:</label>
            <span>{storeDetail.type.charAt(0).toUpperCase() + storeDetail.type.slice(1)}</span>
          </div>
        </div>

        <div className="reviewSection">
          <div className="reviewHeader">
            <h2>Customer Reviews</h2>
            <span className="reviewCount">Total {storeDetail.reviews.length} reviews</span>
          </div>

          <div className="addReviewSection">
            <h3>Write a Review</h3>
            <form onSubmit={handleReviewSubmit}>
              <div className="ratingInput">
                <label>Rating:</label>
                <div className="starRating">
                  {renderStars(newReview.rating)}
                </div>
              </div>
              <TextField
                fullWidth
                multiline
                rows={4}
                variant="outlined"
                placeholder="Share your experience..."
                value={newReview.content}
                onChange={(e) => setNewReview({...newReview, content: e.target.value})}
                className="reviewInput"
              />
              <Button 
                variant="contained" 
                color="primary" 
                type="submit"
                startIcon={<AddComment />}
                className="submitButton"
              >
                Submit Review
              </Button>
            </form>
          </div>

          <div className="reviewList">
            {currentReviews.map((review) => (
              <div key={review.id} className="reviewItem">
                <div className="reviewHeader">
                  <div className="reviewUser">
                    <span className="userName">{review.user}</span>
                    <span className="reviewDate">{review.date}</span>
                  </div>
                  <div className="reviewRating">
                    {renderStars(review.rating)}
                    <span>{review.rating}</span>
                  </div>
                </div>
                <p className="reviewContent">{review.content}</p>
              </div>
            ))}
          </div>
          <div className="paginationContainer">
            <Pagination 
              count={Math.ceil(storeDetail.reviews.length / reviewsPerPage)} 
              page={page} 
              onChange={handlePageChange}
              color="primary"
              size="large"
            />
          </div>
        </div>
      </div>

      <Card className="businessCard">
        <CardContent>
          <Business className="businessIcon" />
          <Typography variant="h5" component="h2">
            Join as a Business
          </Typography>
          <Typography color="textSecondary">
            Start your business journey with us
          </Typography>
          <Button 
            variant="contained" 
            color="primary" 
            className="joinButton"
            onClick={() => navigate('/business/register')}
          >
            Join Now
          </Button>
        </CardContent>
      </Card>
    </div>
  );
} 